export let api = {
  // #ifndef XT_PC
  saveVideoToPhotosAlbum(path, processCallback) {
    console.log('xapi saveVideoToPhotosAlbum')

    // #ifdef MP-WEIXIN
    return new Promise((resolve, reject)=>{
      let downVideoAuth = ()=>{
        uni.$x.notify.showModal({
          title: '授权提示',
          content: '请先授权允许添加到相册',
          confirmText: '去授权',
        }).then(()=>{
          return uni.openSetting({})
        }).then(([err,settingdata])=>{														             
          if(settingdata.authSetting["scope.writePhotosAlbum"]) {
            downVideo1()
          }else{
            resolve()
          }
        }).catch(error=>{
          console.log(error)
          resolve()
        })
      }

      let downVideo1 = ()=>{
        uni.$x.request.download({
          showError: false,
          loading: false,
          url: path,
          baseUrl: '',
          onProgressUpdate: percent=>{
            processCallback&&processCallback(percent)
          }
        }).then(res=>{
          uni.saveVideoToPhotosAlbum({
            filePath: res,
          }).then(([err, res])=>{
            if(err) {
              console.log('xapi saveVideoToPhotosAlbum save:', err)
              reject({
                code: 'saveVideoToPhotosAlbum',
                message: '保存失败',
                data: err
              })
              return
            }
            resolve(true)
          })
        }).catch(err=>{
          console.log('xapi saveVideoToPhotosAlbum download:', err)
          reject({
            code: 'download',
            message: '下载失败',
            data: err
          })
        })
      }

      uni.getSetting({}).then(([err,res])=>{
        if(err) {
          console.log('saveVideoToPhotosAlbum getSetting err:', err)
          reject({
            code: 'getSetting',
            message: '授权失败',
            data: err
          })
          return
        }
        if(res.authSetting['scope.writePhotosAlbum']===false) {
          downVideoAuth()
        }else if(!res.authSetting['scope.writePhotosAlbum']) {
          uni.authorize({
            scope: 'scope.writePhotosAlbum',
          }).then(([err, res])=>{
            if(err) {
              console.log(err);
              if(err.errMsg != 'authorize:fail auth deny') {
                downVideoAuth()
              }else{
                reject({
                  code: 'authorize',
                  message: '授权失败',
                  data: err
                })
              }
              return
            }
            downVideo1()
          })
        }else {
          downVideo1()
        }
      })
      
    })
    // #endif

    // #ifdef H5
    return Promise.reject({
      message: '不支持保存'
    })
    // #endif

    // #ifdef APP-PLUS
    console.log('xapi saveVideoToPhotosAlbum')
    return uni.$x.request.download({
      showError: false,
      loading: false,
      url: path,
      baseUrl: '',
      onProgressUpdate: percent=>{
        processCallback&&processCallback(percent)
      }
    }).then(res=>{
      console.log('xapi saveVideoToPhotosAlbum res:', res)
      return uni.saveVideoToPhotosAlbum({
        filePath: res,
      }).then(([err, res])=>{
        console.log('xapi saveVideoToPhotosAlbum save:', err, res)
        if(err) {
          uni.showModal({
            content: "读写手机存储权限没有开启，是否去开启？",
            success(res) {
              if (res.cancel) return;
              if (uni.getSystemInfoSync().platform === 'ios') {
                var UIApplication = plus.ios.import("UIApplication");
                var application2 = UIApplication.sharedApplication();
                var NSURL2 = plus.ios.import("NSURL");
                var setting2 = NSURL2.URLWithString("app-settings:");
                application2.openURL(setting2);
                plus.ios.deleteObject(setting2);
                plus.ios.deleteObject(NSURL2);
                plus.ios.deleteObject(application2);
              } else {
                var Intent = plus.android.importClass("android.content.Intent");
                var Settings = plus.android.importClass("android.provider.Settings");
                var Uri = plus.android.importClass("android.net.Uri");
                var mainActivity = plus.android.runtimeMainActivity();
                var intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
                intent.setData(uri);
                mainActivity.startActivity(intent);
              }
            }
          })

          throw ({
            code: 'saveVideoToPhotosAlbum',
            message: '保存失败',
            data: err
          })
          return
        }else{
          return true
        }
      })
    }).catch(err=>{
      console.log('xapi saveVideoToPhotosAlbum download:', err)
      throw ({
        code: 'download',
        message: '下载失败',
        data: err
      })
    })
    // #endif
  },
  // #endif
  // #ifdef XT_PC
  download(data, fileName) {
    let anchor = document.createElement("a")
    anchor.href = data;
    anchor.setAttribute("download", fileName);
    anchor.className = "download-js-link";
    anchor.innerHTML = "downloading...";
    anchor.style.display = "none";
    document.body.appendChild(anchor);
    setTimeout(function() {
      anchor.click();
      document.body.removeChild(anchor);
    })
  },
  download1(url, fileName='', options={}) {
    uni.$x.request.download({ url, ...options }).then(res=>{
      var oA = document.createElement("a")
      oA.download = fileName
      oA.href = res.tempFilePath
      document.body.appendChild(oA)
      oA.click()
      oA.remove()
    })
  }
  // #endif
}

export default function($x, {
	apiExtend
}={}, app) {
	Object.assign(api, apiExtend||{})
	$x.api = api
}